<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;

class MakeRepository extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'make:repository {repository} {--P|provider}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new repository, include contract & service';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $repository = $this->argument("repository");

        $register = $this->option("provider");

        if (strpos("Repository", $repository) === false) {
            $repository = $repository . "Repository";
        }

        $repositoryDirectory = app_path("Repositories");
        $repositoryContractDirectory = $repositoryDirectory . "/Contracts";
        $repositoryServiceDirectory = $repositoryDirectory . "/Services";

        $provider = app_path("Providers/RepositoryServiceProvider.php");

        if (!is_dir($repositoryDirectory)) {
            mkdir($repositoryDirectory);
        }

        if (!is_dir($repositoryContractDirectory)) {
            mkdir($repositoryContractDirectory);
        }

        if (!is_dir($repositoryServiceDirectory)) {
            mkdir($repositoryServiceDirectory);
        }

        if (!is_file($provider)) {
            file_put_contents($provider, $this->templateProvider());
        }

        // 创建文件
        if (file_put_contents(
            $repositoryContractDirectory . "/" . $repository . ".php",
            $this->templateContract($repository)
        )) {
            $this->info("Repository Contract created successfully.");
        } else {
            $this->error("Repository Contract created failed.");
        }


        if (file_put_contents(
            $repositoryServiceDirectory . "/" . $repository . "Service.php",
            $this->templateService($repository)
        )) {
            $this->info("Repository Service created successfully.");
        } else {
            $this->error("Repository Service created failed.");
        }

        if ($register) {
            // 注册服务
            if ($this->registerProvider($provider, $repository)) {
                $this->info("RepositoryServiceProvider write successfully.");
            } else {
                $this->error("RepositoryServiceProvider write failed.");
            }
        }

        return true;
    }

    protected function templateContract($repository)
    {
        return <<<CONTRACT
<?php

namespace App\Repositories\Contracts;

interface {$repository}
{
    //
}

CONTRACT;

    }

    protected function templateService($repository)
    {
        return <<<SERVICE
<?php

namespace App\Repositories\Services;

use App\Repositories\Contracts\\$repository;

class {$repository}Service implements {$repository}
{
    //
}

SERVICE;

    }

    protected function templateProvider()
    {
        return <<<PROVIDER
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class RepositoryServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        // 
    }
}

PROVIDER;

    }

    protected function registerProvider($provider, $repository)
    {
        $content = file_get_contents($provider);

        return file_put_contents($provider, preg_replace_callback_array([
            "/(?<use>[\s\S]*?;)[(\r)?\n]+class/" => function ($result) use ($repository) {
                return $this->getUseContent($repository, $result["use"]);
            }, // namespace use
            "/register\(\)[\s\S]*?\{(?<content>[\s\S]*?)\}/" => function ($result) use ($repository) {
                return $this->getBindContent($repository, rtrim($result["content"]));
            }, // register()
        ], $content));
    }

    protected function getBindContent($repository, $content)
    {
        return <<<BIND
register() 
    {{$content}
        \$this->app->bind({$repository}::class, {$repository}Service::class);
    }
BIND;
    }

    protected function getUseContent($repository, $use)
    {
        return <<<USE
{$use}
use App\Repositories\Contracts\\$repository;
use App\Repositories\Services\\{$repository}Service;

class
USE;
    }
}
